package com.rhb.af.web.struts.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.actions.DispatchAction;

import com.rhb.af.bean.BaseItem;
import com.rhb.af.util.BeanTools;

public class BaseDispatchAction extends DispatchAction {

	public BaseDispatchAction() {
		super();
	}

	protected void parseItem(ActionForm objectOfForm, String bean, String gridName, HttpServletRequest request){
		try {
			Object objectOfItem = PropertyUtils.getProperty(objectOfForm, gridName);
			
			List fields = (List)BeanTools.getFields(objectOfItem);
			Set items = (Set)PropertyUtils.getProperty(objectOfForm, bean+"."+gridName+"s");
			
			List list = new ArrayList(items);
			
			Collections.sort(list, new Comparator(){
				public int compare(Object object1, Object object2){
					Date date1 = ((BaseItem)object1).getMadeDate();
					Date date2 = ((BaseItem)object2).getMadeDate();
					return date1.compareTo(date2);
				}
			});
			
			int s = items.size();
			items.clear();
			for(int i=0; i<s ; i++){
				if(request.getParameter(gridName+"_"+i) != null){
					Object item = list.get(i);
					for(int j=0; j<fields.size(); j++){
						String fieldName = (String)fields.get(j);
						Object value = request.getParameter(fieldName +"_"+ i);
						//System.out.println("request.getParameter("+fieldName+"_"+i+")=" + value);
						if(value != null){
							BeanUtils.setProperty(item, fieldName, value);							
						}
					}
					items.add(item);
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

}